﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    ///Removes H-connected pixels. For example:
    ///1  1  1           1  1  1 
    ///0  1  0  becomes  0  0  0 
    ///1  1  1           1  1  1
    /// </summary>
    public class HBreak : BaseForeBackgroundColorFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="HBreak"/> class.
        /// </summary>
        public HBreak()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="HBreak"/> class.
        /// </summary>
        /// <param name="_hbreak">The _hbreak.</param>
        internal HBreak(HBreak _hbreak)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            int y = 0;
            int x = 0;
            int nHeight = _bitmap.Height;
            int nWidth = _bitmap.Width;

            Color[] aColor = new Color[8];

            UnsafeBitmap bitmapCloned = (UnsafeBitmap)_bitmap.Clone();
            int nIndex = 0;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    aColor = Segmentation.GetEnvironmentPixelColorArray(bitmapCloned, x, y, Definitions.EnvironmentPointListClockwise, aColor);

                    bool bHBreakOccurs = ((m_ColorForeground == aColor[0] && m_ColorForeground == aColor[1] && m_ColorForeground  == aColor[2]) 
                                            && (m_ColorForeground == aColor[4] && m_ColorForeground == aColor[5] && m_ColorForeground == aColor[6]))

                                        || ((m_ColorForeground == aColor[2] && m_ColorForeground == aColor[3] && m_ColorForeground == aColor[4])
                                            && (m_ColorForeground == aColor[6] && m_ColorForeground == aColor[7] && m_ColorForeground == aColor[0]));
                    if (bHBreakOccurs)
                    {
                        _bitmap.SetPixel(x, y, m_ColorBackground);
                    }

                }
            }
            bitmapCloned.Dispose();
            return _bitmap; 
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new HBreak(this);
        }
    }
}
